package diycode

import (
	"strconv"
	"strings"
)

// 通过Unicode编码字符串
func EncodeTextByUnicode(text string) string {
	quotedText := strconv.QuoteToASCII(text)
	return quotedText[1 : len(quotedText)-1]
}

// 通过自定义字符项数组编码
func EncodeSlice(text string, format []string, codeSlice CodeSlice) (string, error) {

	formatLen := len(format)
	str := EncodeTextByUnicode(text)

	arr := strings.Split(str, "")
	indexArr := make([]int, len(arr))

	for index, val := range arr {
		if item, err := codeSlice.FindChar(val); err == nil {
			indexArr[index] = item.Index
		} else {
			indexArr[index] = 0
		}
	}

	for index, val := range indexArr {
		numArr := N10toBase(val, formatLen-1)
		strArr := make([]string, len(numArr))
		for index2, val2 := range numArr {
			strArr[index2] = format[val2]
		}
		str := strings.Join(strArr, "")
		arr[index] = str
	}

	res := strings.Join(arr, format[formatLen-1])

	return res, nil
}

// 编码
// 使用默认字符项数组
func Encode(text string, format []string) (string, error) {
	return EncodeSlice(text, format, GetCodeSlice())
}
